package edu.iss.javaproject.controller;

import java.util.Locale;

//import javax.servlet.http.HttpServletRequest;





import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import edu.iss.javaproject.exception.LeaveNotFoundException;
import edu.iss.javaproject.model.Users;
import edu.iss.javaproject.validator.LoginValidator;

@Controller
@SessionAttributes("sessionuser")
public class LoginController {
	
	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	@Autowired
	private LoginValidator loginValidator;
	
	@RequestMapping(value = {"/", "/index", "/login",}, method = RequestMethod.GET)
	public String login(Locale locale) throws LeaveNotFoundException {
		logger.info("Initial login. The client locale is {}.", locale);
		
		return "login";
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String userLogin(@RequestParam(value="username", required=false) String username,
			@RequestParam(value="password", required=false) String password,ModelMap modelMap) {
	
		
		int id = loginValidator.checkNull(username);
		if(id == 0){
			return "redirect:/loginerror";
		}
		Users user = loginValidator.verifyUser(id, password);
		logger.info(user.toString());
		logger.info(user.getRole());
		modelMap.addAttribute("sessionuser", user);
		if(user.getRole().equals("Admin")){
			return "redirect:/adminHome";
		} else if(user.getRole().equals("Employee") || user.getRole().equals("Manager")){
			return "redirect:/staffHome";
		} else {
			return "redirect:/loginerror";
		}
	}	
	
	@RequestMapping(value = "/loginerror", method = RequestMethod.GET)
	public String loginError(Locale locale) {
		logger.info("Logged in failed. The client locale is {}.", locale);
		return "loginError";
	}
	
	@RequestMapping(value = "/Logout", method = RequestMethod.GET)
	public String Logou (Locale locale) {
		
		return "Logout";
	}
	
	
	

}
